package com.cloud.bssp.netty.protocol.userdefined;

import com.cloud.bssp.netty.protocol.userdefined.message.LoginMessage;
import com.cloud.bssp.netty.protocol.userdefined.message.Message;
import com.cloud.bssp.netty.protocol.userdefined.message.MessageCodec;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.util.Date;

/**
 * @description： 服务端
 * @author：weirx
 * @date：2021/11/16 15:16
 * @version：3.0
 */
public class Client {

    public static void main(String[] args) {

        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(worker);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024,12,4,0,0));
                    //引入我们的编解码器
                    ch.pipeline().addLast(new MessageCodec());
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            //组装消息，并发送
                            Message message = new LoginMessage("Tom","123456",new Date());
                            ctx.writeAndFlush(message);
                            super.channelActive(ctx);
                        }
                    });
                }
            });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",8080);
            //阻塞等待连接
            channelFuture.sync();
            //阻塞等待释放连接
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("server error:" + e);
        } finally {
            // 释放EventLoopGroup
            worker.shutdownGracefully();
        }
    }
}
